<template>
  <div class='hawkContent'>
    <hawk-breadcrumb></hawk-breadcrumb>

    <el-row :gutter='20' style='padding-left: 20px;'>
      <el-col :span='4' style="display:flex;align-items: center;">
        <span style="width:100px">业务系统</span>
        <el-input placeholder='请输入业务系统名称' v-model='queryForm.query.name'>
        </el-input>
      </el-col>
      <el-col :span='4'>
        <el-button type='hawkSearch' @click='init(true)'>搜索</el-button>
        <el-button plain @click='reSet'>重置</el-button>
      </el-col>
      <el-col :span='4'
              style='float: right;text-align: right;padding-right: 30px'>
        <el-button type='hawkCreate' @click='editBusiness()'>添加</el-button>
      </el-col>
    </el-row>

    <hawk-table v-model="multipleSelection" :page="queryForm.page"
                :table-data="tableData" :number="true" :options="[
        { key: 'name', label: '业务系统名称',width: 400 },
        { key: 'hostCount', label: '主机数量' },
        { key: 'handle', label: '操作' },
      ]">
      <template #handle="{ row }">
        <span class='hawk-text-btn' @click='editCurrAlarm(row)'>配置告警</span>
        <span class='hawk-text-divider'>|</span>
        <span class='hawk-text-btn' @click='deleteCurrAlarm(row)'>删除告警配置</span>
        <span class='hawk-text-divider'>|</span>

        <span class='hawk-text-btn' @click='editBusiness(row)'>编辑</span>
        <span class='hawk-text-divider'>|</span>
        <span class='hawk-text-btn' @click='delBusiness(row)'>删除</span>
        <span class='hawk-text-divider'>|</span>
        <span class='hawk-text-btn' @click='selectHosts(row)'>选择主机</span>
      </template>
    </hawk-table>

    <div class='bottom-btns'>
      <div class="bottom-btns-left">
        <div class="bottom-btns-left-num">
          {{ multipleSelection.length }} 选择
        </div>
        <el-button type="hawkDelete" @click='delMul()'>批量删除</el-button>
      </div>
      <el-pagination background @size-change='handleSizeChange'
                     @current-change='handleCurrentChange'
                     :current-page.sync='queryForm.page.current'
                     :page-sizes='[10, 20, 50, 100]'
                     :page-size='queryForm.page.size'
                     v-if="tableData.length <= queryForm.page.size"
                     layout=' prev, pager, next,sizes' :total='total'>
      </el-pagination>
    </div>

    <!-- 业务系统弹框 -->
    <el-dialog :title='formTitle' :visible.sync='businessVisible'
               :close-on-click-modal='false' @close='businessClosed'>
      <!-- 内容主题区 -->
      <el-form :model='businessForm' :rules='businessRules' ref='businessRef'
               label-width='90px' label-position="top">
        <el-form-item label="业务系统名称" prop="name">
          <el-input type="text" v-model="businessForm.name"
                    placeholder="请输入业务系统名称"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot='footer' class='dialog-footer'>
        <el-button @click='businessVisible = false'>取 消</el-button>
        <el-button type='primary' @click='businessSave'>确 定</el-button>
      </span>
    </el-dialog>

    <!-- 配置告警弹框 -->
    <el-dialog title='告警配置' :visible.sync='alarmVisible'
               :close-on-click-modal='false' @close='alarmClosed'>
      <!-- 内容主题区 -->
      <el-form :model='alarmData' label-position="right" :rules='addFormRules'
               ref='alarmRef' label-width='100px'>

        <el-form-item label="告警分组" prop="alarmGroupIds">
          <el-select v-model="alarmData.alarmGroupIds" multiple
                     placeholder="请选择告警分组">
            <el-option v-for="item in alarmGroupList" :key="item.id"
                       :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="告警用户" prop="userIds">
          <el-select v-model="alarmData.userIds" multiple placeholder="请选择告警用户">
            <el-option v-for="item in alarmPeopleList" :key="item.id"
                       :label="item.nickName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="告警间隔" prop="delay">
          <el-input type="number" :min="1" v-model.number="alarmData.delay"
                    placeholder="请输入告警间隔"></el-input>
        </el-form-item>

        <el-form-item label="间隔单位" prop="unit">
          <el-select clearable v-model="alarmData.unit" placeholder="单位">
            <!-- <el-option key="s" label="秒" value="s"></el-option> -->
            <el-option key="m" label="分钟" value="m"></el-option>
            <el-option key="h" label="小时" value="h"></el-option>
            <el-option key="d" label="天" value="d"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="告警次数" prop="count">
          <el-input type="number" :min="1" v-model.number="alarmData.count"
                    placeholder="请输入告警次数"></el-input>
        </el-form-item>

      </el-form>
      <!-- 底部区 -->
      <span slot='footer' class='dialog-footer'>
        <el-button @click='alarmClosed'>取 消</el-button>
        <el-button type='primary' @click='alarmSave'>确 定</el-button>
      </span>
    </el-dialog>

    <!-- “选择主机”组件 当选择主机后@主动调用业务系统this.init()的方法，页面自动刷新 -->
    <choosehosts ref="chooseHosts" @repeatInit="init"></choosehosts>

  </div>
</template>
<script>
import { getList, doDelete, doAdd, doEdit, getAlarmBybsId, deleteAlarm, addAlarm, editAlarm }
  from '@/api/monitor/config/business/index.js'
import { getList as groupList, getAllUser } from "@/api/monitor/config/group"
import { getAll as userList } from "@/api/system/user"
import Choosehosts from './components/Choosehosts.vue'

export default {
  components: { Choosehosts },
  //import引入的组件需要注入到对象中才能使用",
  name: "Index",
  data () {


    let inHaveName = (rule, value, callback) => {


      let find = this.tableData.find(el => {
        return el.name == value
      })
      if (find) {
        callback(new Error('名称已经存在'))
      } else {
        callback()
      }

    }

    //这里存放数据",
    return {
      confirmgTitle: '',
      formTitle: '',
      id: 0,
      businessVisible: false,
      alarmVisible: false,
      hostsVisible: false,
      multipleSelection: [],
      // 配置告警
      alarmData: {
        userIds: [],
        alarmGroupIds: [],
        delay: '',
        unit: '',
        count: '',
        businessid: '', // 对应业务系统的ID
        id: '', // 当前告警的ID 
      },
      // 业务系统 新增/编辑 向后端传递的数据
      businessForm: {
        name: '',
        id: '',
      },
      //业务系统验证
      businessRules: {
        name: [
          {
            required: true, message: '请输入业务系统名称', trigger: 'blur'
          },
          { validator: inHaveName, trigger: 'blur' }

        ],
      },
      addFormRules: {

        // alarmGroupIds: [
        //   { message: '请选择分组', trigger: 'change' },
        // ],

        // userIds: [
        //   { message: '请选择用户', trigger: 'change' },
        // ],

        delay: [
          { required: true, message: '请输入告警间隔', trigger: 'blur' },
        ],

        count: [
          { required: true, message: '请输入告警次数', trigger: 'blur' },
        ],
        unit: [
          { required: true, message: '请输入告警单位', trigger: 'blur' },
        ],

      },
      tableData: [],
      total: 0,
      queryForm: {
        query: {
          name: '',
        },
        page: {
          current: 1,
          size: 10
        }
      },
      // 告警分组列表
      alarmGroupList: [],
      // 告警用户列表
      alarmPeopleList: [],
    }
  },
  //监听属性 类似于data概念",
  computed: {
    cellStyle () {
      return {
        padding: '8px 0'
      }
    }
  },
  //监控data中的数据变化",
  watch: {},
  //方法集合",
  methods: {
    //业务系统分页条件查询
    async init (type) {
      if (type) this.queryForm.page.current = 1
      const res = await getList(this.queryForm)
      console.log(res, '------业务系统分页查');
      if (res.code == 20000) {

        this.tableData = res.data.records
        this.total = res.data.total
      }
    },
    reSet () {
      this.queryForm = this.$options.data().queryForm
      this.init()
      this.multipleSelection = []
    },
    // 添加/修改业务系统
    async editBusiness (row) {
      // console.log(row)
      if (row) {
        this.formTitle = '编辑业务系统'
        this.businessForm = Object.assign({}, row)
      } else {
        this.formTitle = '新增业务系统'
      }
      this.businessVisible = true
    },
    // 保存业务系统
    async businessSave () {
      this.$refs.businessRef.validate(async (valid) => {
        console.log(valid)
        if (!valid) return
        //调用方法
        if (this.businessForm.id) {
          //业务系统修改
          const res = await doEdit(this.businessForm)
          console.log(res, '---------修改业务系统结果');
          if (res.code == 20000) {
            this.$message({
              type: 'success',
              message: '编辑成功'
            })
          } else {
            this.$message({
              type: 'waring',
              message: res.message
            })
          }
        }
        else {
          //业务系统新增	         
          const res = await doAdd(this.businessForm)
          console.log(res)
          if (res.code == 20000) {
            this.$message({
              type: 'success',
              message: '添加成功'
            })
          } else {
            this.$message({
              type: 'waring',
              message: '添加失败，业务系统名称重复！'
            })
          }
        }
        this.businessVisible = false
        this.init()
      })
    },

    async deleteCurrAlarm (row) {

      this.$confirm(`确认删除?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async () => {


        let ret = deleteAlarm(row.id)
        if (ret.code == 20000) {
          this.$msg({
            type: 'success',
            message: '删除成功'
          })
        }
      })

      this.init()

    },

    // 先查询配置告警
    async editCurrAlarm (row) {
      console.log(row, "row")
      if (row.hostCount < 1) {
        this.$msg({
          type: 'warn',
          message: '请先添加主机'
        })
        return
      }
      this.formTitle = '告警配置'
      this.alarmVisible = true

      // Object.assign(this.alarmData,row)
      this.alarmData.businessid = row.id


      const ret = await getAlarmBybsId(row.id)
      console.log(ret, '----获得告警');
      if (ret.code == 20000) {
        let data = ret.data
        // Object.assign(this.alarmData, ret.data)
        this.alarmData = {
          alarmGroupIds: ((() => {

            if (data.alarmGroup != null) {
              return data.alarmGroup.map(el => el.id)
            } else {
              return null
            }

          })()),

          businessid: row.id, // 对应业务系统的ID
          count: data.alarm == null ? '' : data.alarm.count,
          delay: data.alarm == null ? '' : data.alarm.delay,
          hostid: data.alarm == null ? '' : data.alarm.hostid,
          id: data.alarm == null ? '' : data.alarm.id, // 当前告警的ID 
          unit: data.alarm == null ? '' : data.alarm.unit,

          userIds: (() => {
            if (data.sysUser != null) {
              return data.sysUser.map(el => el.id)
            }
            return null

          })(),

        }

        console.log(this.alarmData.alarmGroupIds);

      }
    },
    // 保存告警信息
    alarmSave () {
      this.$refs.alarmRef.validate(async (valid) => {
        if (!valid) return
        // || this.alarmData.userIds.length < 1 && this.alarmData.alarmGroupIds.length < 1 

        if (this.alarmData.userIds == null && this.alarmData.alarmGroupIds == null
        ) {

          this.$message({
            type: 'warning',
            message: '告警分组与告警用户不可都为空'
          })
          return
        }


        //判断告警间隔或告警次数不为负数或0
        if (this.alarmData.delay < 1 || this.alarmData.count < 1) {
          this.$message({
            type: 'warning',
            message: '告警间隔或告警次数输入不可为0或负数'
          })
          return
        }

        console.log(this.alarmData, '---提交的数据');

        //调用方法
        // if (this.alarmData.id) {
        //告警配置修改

        //   const res = await editAlarm(this.alarmData)

        //   console.log(res, "res")

        //   if (res.code == 20000) {
        //     this.$message({
        //       type: 'success',
        //       message: '修改成功'
        //     })
        //   }

        // } else {
        //告警配置新增
        let ret = await addAlarm(this.alarmData)
        console.log(ret);
        if (ret.code == 20000) {
          this.$message({
            type: 'success',
            message: '修改成功'
          })
          // }

        }
        this.alarmVisible = false
        this.init()
      })
    },
    selectHosts (row) {
      this.$refs.chooseHosts.open(row.id)
    },
    //批量删除业务系统
    async delMul () {
      if (this.multipleSelection.length > 0) {
        this.$confirm('是否删除所有选中业务系统?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
          .then(async () => {
            let list = [];
            this.multipleSelection.forEach((item) => {
              list.push(item.id)
            })


            let ret = await doDelete(list);
            if (ret.code == 20000) {

              let type = ''
              if (ret.data || ret.message.indexOf('成功') != -1) {
                ret.message = '删除成功'
                type = 'success'
              } else {
                type = 'error'
              }

              this.$message({
                type: type,
                message: ret.message,
              })

              if (this.multipleSelection.length == this.tableData.length) {

                this.queryForm.page.current = this.queryForm.page.current - 1
                if (this.queryForm.page.current < 1) {
                  this.queryForm.page.current = 1
                }

              }

              this.multipleSelection = []
              console.log('-------------init---');
              this.init()

            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除',
            })
          })
      }
    },
    //移除单个业务系统
    async delBusiness (row) {
      // console.log(row)
      row.hostNum > 0 ? this.confirmgTitle = '该业务系统下有主机是否需要删除' : this.confirmgTitle = '是否删除该业务系统'
      // if(row.hostNum > 0){
      //    this.$confirm('该业务系统下存在主机, 是否继续?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消'
      // })
      // }
      this.$confirm(`${this.confirmgTitle},是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async () => {
        let ret = await doDelete([row.id])
        console.log(ret);

        if (ret.code == 20000) {

          let type = ''
          if (ret.data || ret.message.indexOf('成功') != -1) {
            ret.message = '删除成功'
            type = 'success'
          } else {
            type = 'error'
          }
          this.$message({
            type: type,
            message: ret.message,
          })

          if (this.tableData.length == 1) {
            this.queryForm.page.current = this.queryForm.page.current - 1
            if (this.queryForm.page.current < 1) {
              this.queryForm.page.current = 1
            }
          }

          this.multipleSelection = []
          this.init()

        }

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSizeChange (val) {
      // console.log(val)
      this.queryForm.page.size = val
      this.init()
    },
    handleCurrentChange (val) {
      // console.log(val,"handleCurrentChange")
      this.queryForm.page.current = val
      this.init()
    },
    // 多选
    // handleSelectionChange(val){
    //   this.multipleSelection = val
    // },
    // 新增/修改弹框关闭
    businessClosed () {
      this.businessForm = this.$options.data().businessForm;
      this.addDialogVisible = false
    },
    //告警弹框关闭
    alarmClosed () {
      this.alarmData = this.$options.data().alarmData;
      this.alarmVisible = false
    },
    //选择主机弹框关闭
    chooseClosed () {
      this.addForm2 = this.$options.data().addForm2
      this.addDialogVisible = false
    },
  },
  //生命周期 - 创建之前",数据模型未加载,方法未加载,html模板未加载
  beforeCreate () {

  },

  //生命周期 - 创建完成（可以访问当前this实例）",数据模型已加载，方法已加载,html模板已加载,html模板未渲染
  async created () {
    this.init()
    groupList(this.queryForm)
      .then(ret => {
        console.log(ret, '----警告分组信息');
        this.alarmGroupList = ret.data.records
      })
    // this.alarmPeopleList = await userList()
    // console.log(this.alarmGroupList, "分组")

    getAllUser()
      .then(ret => {
        console.log(ret, '---------所有的用户');
        if (ret.code == 20000) {
          this.alarmPeopleList = ret.data
        }
      })

  },

  //生命周期 - 挂载完成（可以访问DOM元素）",html模板已渲染
  mounted () {

  }

}
</script>

<style lang='less' scoped>
</style>
